package cn.yr.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.yr.common.core.domain.dto.SysUserDto;
import cn.yr.common.core.domain.entity.SysRole;
import cn.yr.common.core.domain.entity.SysUser;
import cn.yr.common.core.manager.AuthCacheManager;
import cn.yr.system.mapper.LoginMapper;
import cn.yr.system.mapper.SysUserMapper;
import cn.yr.system.service.ILoginService;
import cn.yr.system.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author Lang 1102076808@qq.com
 * @description
 * @date 2020-06-20 08:24
 */
@Service
public class LoginServiceImpl  extends ServiceImpl<SysUserMapper, SysUser> implements ILoginService{

	@Resource
	private LoginMapper loginMapper;

	@Autowired
	private ISysMenuService menuService;

	@Autowired
	protected AuthCacheManager authCacheManager;

	@Override
	public SysUser getByUsername(String username) {
		return loginMapper.queryByUsername(username);
	}

	@Override
	public SysUserDto initUser(SysUser user) {
		/** 缓存用户信息与权限*/
		Set<String> userPermissions = menuService.selectMenuPermsByUserId(user.getUserId());
		SysUserDto sysUserDto = new SysUserDto();
		sysUserDto.setSysUser(user);
		sysUserDto.setPerms(userPermissions);
		List<SysRole> roleList = loginMapper.listRole( user.getUserId());
		sysUserDto.setSysRoles(roleList);
		return sysUserDto;
	}

	@Override
	public String generatePassword(String passwordText, String salt) {
		return SecureUtil.sha256(passwordText+salt);
	}

	@Override
	public String generateSalt() {
		return RandomUtil.randomString(6);
	}

	@Override
	public SysUser getUserByUuid(String uuid) {
		return loginMapper.queryByUuid(uuid);
	}

	@Override
	public void addAuthUser(AuthUser authUser) {
		SysUser sysUser = new SysUser();
		BeanUtil.copyProperties(authUser,sysUser,true);

		sysUser.setOauthType(authUser.getSource());
		if(ObjectUtil.isNotEmpty(authUser.getGender())){
			sysUser.setSex(authUser.getGender().getCode());
		}
		if(StrUtil.isEmpty(sysUser.getUserName())){
			String prefix = "south-wind";
			sysUser.setUserName(prefix+RandomUtil.randomString(6));
		}
		if(StrUtil.isEmpty(sysUser.getNickName())){
			sysUser.setNickName(sysUser.getUserName());
		}
		sysUser.setUserType("1");
		sysUser.setCreateTime(new Date());
		loginMapper.insert(sysUser);
	}

	@Override
	public void updateUser(Long uid) {
		SysUser sysUser = loginMapper.selectById(uid);
		authCacheManager.putUser(uid.toString(),this.initUser(sysUser));
	}
}
